package com.risk.convert;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 通用类型装换器
 *
 * @author yangjingjing
 */
@Slf4j
public class BaseConvert {

    public static <T> T convertObject(Object object, Class<T> clazz) {
        log.info("convertObject object:{} to {}", object, clazz);
        if(null==object){
            return null;
        }
        T result = null;
        try {
            result = (T) clazz.newInstance();
        } catch (Exception e) {
            log.info("convertObject exception [{}]", e);
        }
        if (object != null) {
            BeanUtils.copyProperties(object, result);
        }
        return result;
    }

    public static <T> List<T> convertList(List list, Class<T> clazz) {
        log.info("convertObject object:{} to {}", list, clazz);
        List<T> newArrayList = new ArrayList<>();
        list.stream().forEach(e -> {
                    T t = BaseConvert.convertObject(e, clazz);
                    newArrayList.add(t);
                }
        );
        return newArrayList;
    }
}
